module("luci.controller.login.file", package.seeall)

local fs = require "nixio.fs"
local uci = require "luci.model.uci".cursor()

function index()
    local page   = node("login","file")
    page.target  = firstchild()
    page.title   = ("")
    page.order   = 100
    page.sysauth = "root"
    page.sysauth_authenticator = "jsonauth"
    page.index = true

    entry({"login", "file", "upload"}, call("upload"), nil)
end

-- 本地升级
function upload()
	local data={}
	local code=1
	local flag=1
	local name=""
	local msg="Success"
	local uploadFile=""
	
	local canupload = true
    --local Path = luci.sys.exec("cat /proc/mounts | grep '/dev/mmcblk' | awk '{print $2}'")
	local Path = "/tmp"
    local filesize = tonumber(luci.http.getenv("CONTENT_LENGTH"))

    luci.http.setfilehandler(
        function(meta, chunk, eof)
            if canupload then
                if not fp then
                    if meta then
						name=meta.name
						local uploadFile=Path.."/"..meta.name.."/"..meta.type
						
						if flag then
							fs.unlink(uploadFile)
							flag=0
						end
						--local filetype = luci.http.formvalue("filetype")
						--local filename = luci.http.formvalue("filename")
						
						fp = io.open(uploadFile, "w")
                    else
						code=1
						msg="文件无法识别,拒绝上传"
					end
                end
                if chunk then
                    fp:write(chunk)
                end
                if eof then
                    fp:close()
					code=0
					msg="上传成功"
                end
            end
        end
    )
	
	luci.http.formvalue(name)
	
	data ={
		code=code,
		msg=msg
	}
	luci.http.prepare_content("application/json")
	luci.http.write_json(data)
	
--	if code == 0 then
--		os.exec
--	end
end
